<?php
/**
 * Created by JetBrains PhpStorm.
 * User: zhouyang
 * Date: 13-7-15
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */

class UserAction extends Action{
    private $M_users;
    private $M_cates;
    private $M_roles;
    private $M_user_has_roles;
    private $M_cate_has_users;

    private $A_role;
    private $A_cate;

    //免费服务器 多次刷新丢失session 添加
    private $session_user_id = '';

    /**
     * 构造方法
     * 初始化
     */
    public function __construct(){
        $this->M_users = Model::getInstance('users');
        $this->M_cates = Model::getInstance('cates');
        $this->M_roles = Model::getInstance('roles');
        $this->M_user_has_roles = Model::getInstance('user has roles');
        $this->M_cate_has_users = Model::getInstance('cate has users');

        $this->A_role = Action::getInstance('role');
        $this->A_cate = Action::getInstance('cate');
    }

    public function isAction($action_url){
        $user_id = $this->getCurrUserId();
        $ret = $this->M_users->isAction($action_url,$user_id);
        if($ret == false){
            $data = array(
                "statusCode"=>"300",
                "message"=>"您没有访问权限，如需使用请联系系统管理员！",
            );
            echo Response::JSON(300,$data);
            exit;
        }
    }

    public function getCurrUserId(){
        $this->session_user_id = $this->session()->get('user_id');
        if(empty($this->session_user_id)){
            if(sha1($_COOKIE[SITE_PREFIX.'user_account'].$_COOKIE[SITE_PREFIX.'user_id'].return_ip().SHA1_CODE) == $_COOKIE[SITE_PREFIX.'user_code']){
                $this->session_user_id = $_COOKIE[SITE_PREFIX.'user_id'];
            }
        }

        return $this->session_user_id;
    }

    public function indexRefer(){
        $user_info = $this->verificationIsLogin();

        if(!empty($user_info)){//没有登录用户信息
            $this->indexData($user_info);
        }
    }

    /**
     * 检查用户是否登录
     * @return bool
     */
    public function isLogin(){
        $session_user_id = $this->getCurrUserId();

        if($_COOKIE[SITE_PREFIX.'user_id'] && $session_user_id == $_COOKIE[SITE_PREFIX.'user_id']){
            return true;
        }else{
            l('过期时候的COOKIE：'.$_COOKIE[SITE_PREFIX.'user_id'].'，SESSION：'.$this->session()->get('user_id'),'logout');
        }
        return false;
    }

    /**
     * 验证用户是否登录，并返回用户信息
     * @return array
     */
    public function verificationIsLogin(){
        $is_login = $this->isLogin();

        if(!$is_login){
            if($this->input()->isAjax()){
                echo '{"statusCode":"301"}';
                exit;
            }else{
                redirect(SITE_URL . 'index.php?a=user&m=login');
            }
        }
        $session_user_id = $this->getCurrUserId();
        if($session_user_id){
            return $this->M_users->getUserById($session_user_id);
        }
        return array();
    }

    //用户登录入口 及 用户登录系统
    public function login(){

        //判断是否提交
        $submit = $this->input()->post('submit');

        if(!isset($submit)){
            Template::show('Login/index.php');
            exit;
        }

        //验证登陆信息
        $account = $this->input()->post('account');
        $password = substr(md5($this->input()->post('password').PASSWORD_PREFIX),0,16);
        $verify = strtolower($this->input()->post('verify'));
        $sess_verify = $this->session()->get('verify');

//        if(!isset($verify) || $verify != $sess_verify){
//            $data = array(
//                'message'=>'登录失败，验证码错误！',
//                'url'    =>SITE_URL . 'index.php?a=user&m=login',
//            );
//            Template::show('Public/error.php',$data);
//        }
        $this->session()->del('verify');

        $user_info = $this->M_users->login($account,$password);

        if($user_info){
            $this->session()->set('user_id',$user_info['user_id']);
            setcookie(SITE_PREFIX.'user_id', $user_info['user_id'], time()+3600*24, '/', CURR_DOMAIN);
            setcookie(SITE_PREFIX.'user_account', $user_info['account'], time()+3600*24, '/', CURR_DOMAIN);
            setcookie(SITE_PREFIX.'user_code', sha1($user_info['account'].$user_info['user_id'].return_ip().SHA1_CODE), time()+3600*24, '/', CURR_DOMAIN);
            //redirect(SITE_URL . 'index.php'); 登陆成功
            $this->indexData($user_info);
        }else{
            $data = array(
                'message'=>'登录失败，用户名或密码错误！',
                'url'    =>SITE_URL . 'index.php?a=user&m=login',
            );
            Template::show('Public/error.php',$data);
        }
    }

    /**
     * 我的主页
     */
    public function myHome(){
        Template::show('Index/my_home.php');
    }

    /**
     * 编程格言
     */
    public function programMaxim(){
        Template::show('Index/program_maxim.php');
    }

    //用户退出
    public function logout(){
        $this->session()->delete('user_id');
        setcookie(SITE_PREFIX . 'user_id', NULL, time() - 3600 * 24, '/', CURR_DOMAIN);
        setcookie(SITE_PREFIX . 'user_account', NULL, time() - 3600 * 24, '/', CURR_DOMAIN);
        setcookie(SITE_PREFIX . 'user_code', NULL, time() - 3600 * 24, '/', CURR_DOMAIN);

        redirect(SITE_URL . 'index.php?a=user&m=login');
    }

    //登录成功后台显示首页相关信息
    public function indexData($user_info){
        $tree_html = $this->A_cate->getTree($user_info['user_id']);
        $user_has_roles = $this->A_role->getUserHasRoles($user_info['user_id']);
        $user_cate_ids = $this->A_cate->getCateIdsByUserId($user_info['user_id']);
        $data = array(
            'user_info'=>$user_info,
            'tree_html'=>$tree_html,
            'user_has_roles'=>$user_has_roles,
            'user_cate_ids'=>$user_cate_ids
        );

        Template::show('Index/index.php',$data);
    }

    //首页
    public function index(){
        //取得博文列表
        $curr_page = (int)$this->input()->post('pageNum',1);
        $per_page  = (int)$this->input()->post('numPerPage',30);
        $account = $this->input()->post('account');

        $filter = array();

        if($account){
            $filter['account'] = $account;
        }

        $user_list = $this->M_users->getUserList($curr_page,$per_page,$filter);

        $data = array(
            'user_list'=>$user_list,
        );
        Template::show('User/index.php',$data);
    }

    public function add(){
        Template::show('User/add.php');
    }

    public function delUser(){
        $user_id = $this->input()->get('user_id');
        $ret = $this->M_users->delUser($user_id);

        if($ret){
            $this->M_cate_has_users->delByUserId($user_id);
            $this->M_user_has_roles->delByUserId($user_id);
            $data = array(
                "statusCode"=>"200",
                "navTabId"=>"user",
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"删除失败",
            );
            echo Response::JSON(300,$data);
        }
        exit;
    }

    public function edit(){
        $user_id = (int)$this->input()->get('user_id');

        $editrole = (int)$this->input()->get('editrole',1);

        $user_info = $this->M_users->getUserById($user_id);

        $roles = $this->M_users->getUserRoles($user_id);

        $_role_ids = $_role_names = array();

        foreach($roles as $v){
            $_role_ids[] = $v['role_id'];
            $_role_names[] = $v['role_name'];
        }

        $is_super_admin = $this->M_users->isSuperAdmin($this->session()->get('user_id'));

        $data = array(
            'role_ids'=>implode(',',$_role_ids),
            'role_names'=>implode(',',$_role_names),
            'user_info'=>$user_info,
            'editrole'=>$editrole,
            'is_super_admin'=>$is_super_admin
        );

        Template::show('User/edit.php',$data);
    }


    public function editRole(){
        $user_id = (int)$this->input()->get('user_id');

        $cates = $this->M_users->getUserCates($user_id);

        $cate_ids = array();
        foreach($cates as $v){
            $cate_ids[] = $v['cate_id'];
        }

        $menu_arr = $this->M_cates->getTree();

        $data = array(
            'user_id'=>$user_id,
            'menu_arr'=>$menu_arr,
            'cate_ids'=>$cate_ids,
        );

        Template::show('User/user_cate_tree.php',$data);
    }

    public function setRole(){
        $user_id = (int)$this->input()->get('user_id');
        $role_name = (int)$this->input()->post('role_name');

        $filter = array();

        if($role_name){
            $filter['role_name'] = $role_name;
        }

        $roles = $this->M_roles->getRoles($filter);
        $user_roles = $this->M_users->getUserRoles($user_id);

        $role_ids = array();
        foreach($user_roles as $v){
            $role_ids[] = $v['role_id'];
        }

        $data = array(
            'user_id'=>$user_id,
            'roles'=>$roles,
            'role_ids'=>$role_ids,
        );

        Template::show('User/user_role.php',$data);
    }

    public function getUserHasRoles($user_id){
        return $this->A_roles->getUserHasRoles($user_id);
    }

    public function ajaxAdd(){
        $account = $this->input()->post('account');
        $password = $this->input()->post('password');
        $repassword = $this->input()->post('repassword');
        $email = $this->input()->post('email');

        if(!$account){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写用户名",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        if(!$email){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写联系邮箱",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        if(!$password || $password != $repassword){
            $data = array(
                "statusCode"=>"300",
                "message"=>"两次输入的密码不一致",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $tel = $this->input()->post('tel');

        $ret = $this->M_users->addUser($account,$password,$email,$tel);

        $role_ids = $this->input()->post('role_ids',false);

        if($ret){

            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_user_has_roles->addUserHasRoles($ret,$v);
                    }
                }
            }

            $data = array(
                "statusCode"=>"200",
                "message"=>"添加成功",
                "navTabId"=>"user",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"添加失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function ajaxEdit(){

        $user_id = $this->input()->post('user_id');
        $password = $this->input()->post('password');


        $user_info = $this->M_users->getUserById($user_id);

        $_password = substr(md5($password.PASSWORD_PREFIX),0,16);
        if( $user_info['password'] != $_password){
            $data = array(
                "statusCode"=>"300",
                "message"=>"请重新输入新密码",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $is_super_admin = $this->M_users->isSuperAdmin($user_info['user_id']);

        if(!$is_super_admin){
            $data = array(
                "statusCode"=>"300",
                "message"=>"超级管理员密码不能被修改",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $newpassword = $this->input()->post('newpassword');
        $repassword = $this->input()->post('repassword');

        if($password && $newpassword != $repassword){
            $data = array(
                "statusCode"=>"300",
                "message"=>"两次输入的密码不一致",
            );
            echo Response::JSON($data);
            exit;
        }

        $account = $is_super_admin ? $this->input()->post('account') : $user_info['account'];
        $email = $this->input()->post('email');
        $tel = $this->input()->post('tel');
;
        $ret = $this->M_users->updateUser($user_id,$account,$newpassword,$email,$tel);

        $role_ids = $this->input()->post('role_ids',false);

        if($ret){
            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                $this->M_user_has_roles->delByUserId($user_id);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_user_has_roles->addUserHasRoles($user_id,$v);
                    }
                }
            }
            $data = array(
                "statusCode"=>"200",
                "message"=>"修改成功",
                "navTabId"=>"user",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"修改失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function ajaxSetUserRole(){

        $cate_ids = $this->input()->post('cate_ids');
        $user_id = $this->input()->post('user_id');

        $this->M_cate_has_users->delByUserId($user_id);

        if($cate_ids){
            $cate_ids = array_unique($cate_ids);
            foreach($cate_ids as $v){
                if($v){
                    $this->M_cate_has_users->addCateHasUsers($v,$user_id);
                }
            }
        }

        $data = array(
            "statusCode"=>"200",
            "message"=>"权限设置成功!",
            "navTabId"=>"user",
            "callbackType"=>"closeCurrent"
        );
        echo Response::JSON(200,$data);
    }

    public function ajaxUserRole(){
        $role_ids = $this->input()->post('role_ids');
        $user_id = $this->input()->post('user_id');

        if(!$role_ids){
            $data = array(
                "statusCode"=>"300",
                "message"=>"至少选择一个角色！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $this->M_user_has_roles->delByUserId($user_id);
        if($role_ids){
            $role_ids = array_unique($role_ids);
            foreach($role_ids as $v){
                if($v){
                    $this->M_user_has_roles->addUserHasRoles($user_id,$v);
                }
            }
        }

        $data = array(
            "statusCode"=>"200",
            "message"=>"角色设置成功!",
            "navTabId"=>"user",
            "callbackType"=>"closeCurrent"
        );
        echo Response::JSON(200,$data);
    }
}